<template>
  <div>
    <SectionTitle title="申请信息" style="margin-bottom: 16px;" />
    <el-form
      ref="applyInfoForm"
      :rules="rules"
      :model="applyInfo"
      :class="{'mobile-el-form': showMobilePage}"
      :label-position="showMobilePage?'left':'right'"
      class="lineHeight32 apply-info-form"
      label-width="110px">
      <el-row class="response-el-row" type="flex">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="创建人" prop="creatorId">
            <selectWithUserLoad
              v-model="applyInfo.creatorObj"
              :default-list="defaultUserList"
              :show-check-user="true"
              :disabled="true"
              value-type="object"
              key-name="id"
              label-name="userName"
              filterable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请部门" prop="proposerDepartmentId">
            <el-cascader
              v-model="applyInfo.proposerDepartmentId"
              :show-all-levels="false"
              :options="deptList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              placeholder="请选择申请部门"
              size="small"
              collapse-tags
              filterable
              clearable>
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name || '--' }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请人" prop="proposer">
            <selectWithUserLoad
              v-model="applyInfo.proposerObj"
              :show-check-user="true"
              :default-list="defaultProposerList"
              value-type="object"
              key-name="id"
              label-name="userName"
              filterable
              placeholder="请选择申请人"
              clearable
              @change="handleProposerChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请范围" prop="rangeList" class="range-radio-group">
            <el-checkbox-group v-model="applyInfo.rangeList" @change="onRangeChange">
              <template v-for="option in rangeOptions">
                <el-checkbox :key="option.value" :label="option.value">{{ option.label }}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请说明" prop="description">
            <el-input v-model="applyInfo.description" :maxlength="200" resize="none" placeholder="请输入申请说明" type="textarea" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="附件" prop="attachment">
            <upAttachment
              ref="uploadAttachment"
              :hide-confirm="true"
              :file-list="applyInfo.attachment"
              import-api="/common/file/upload"
              btn-text="上传文件"
              @complateSetData="completeSetData($event, 'attachment')"
              @removeFileList="removeFileList($event, 'attachment')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import upAttachment from '@/components/Common/upAttachment';
import { getDepartmentAll } from '@/api/config';
import mobileCreate from '@/mixins/mobileCreate';
import { mapState } from 'vuex';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';
export default {
  components: { selectWithUserLoad, SectionTitle, upAttachment },
  mixins: [mobileCreate],
  props: {
    detailData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      LEVEL_CHANGE_TYPE,
      applyInfo: {
        proposerObj: {},
        avatar: '',
        applicantId: null, // 申请人
        proposer: null, // 申请人名字
        proposerDepartmentId: null, // 申请部门
        rangeList: [],
        attachment: [] // 附件
      }, // 申请信息
      deptList: [],
      defaultProposerList: [],
      rules: {
        'proposerDepartmentId': [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        'proposer': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'rangeList': [{ required: true, message: '请选择申请范围', trigger: 'change' }],
        'description': [{ required: true, message: '请输入申请说明', trigger: 'blur' }]
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    rangeOptions() {
      return [
        { value: LEVEL_CHANGE_TYPE.LEVEL, label: '调整等级' },
        { value: LEVEL_CHANGE_TYPE.AMOUNT, label: '调整额度' },
        { value: LEVEL_CHANGE_TYPE.PERIOD, label: '调整账期' }
      ];
    },
    defaultUserList() {
      const { creatorId, creator } = this.applyInfo;
      return creatorId && creator ? [{ id: creatorId, userName: creator }] : [];
    }
  },
  watch: {
    detailData: {
      handler(val) {
        if (val) {
          this.defaultProposerList = [{ id: val.proposerObj.id, userName: val.proposerObj.userName }];
          this.applyInfo = val;
        }
      },
      deep: true,
      immediate: false
    }
  },
  created() {
    this.getDeptList();
    this.setDefaultProposer();
  },
  methods: {
    getFormData() {
      const params = _.cloneDeep(this.applyInfo);
      params.rangeIds = this.applyInfo.rangeList.join(',');
      return params;
    },
    getDeptList() {
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
      });
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['applyInfoForm'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    onRangeChange() {
      this.$emit('onRangeChange', this.applyInfo.rangeList);
    },
    setDefaultProposer() {
      const { id, userName, avatar } = this.userInfo;
      this.applyInfo.creatorId = id;
      this.applyInfo.creator = userName;
      this.applyInfo.avatar = avatar;
      this.applyInfo.creatorObj = {
        id,
        userName,
        avatar
      };
      this.applyInfo.proposerObj = {
        id,
        userName,
        avatar
      };
      this.applyInfo.proposer = userName;
      this.applyInfo.applicantId = id;
      this.defaultProposerList = [this.applyInfo.proposerObj];
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        const proposerDepartmentId = this.getFirstDepartment(this.userInfo.departmentAry);
        this.applyInfo.proposerDepartmentId = proposerDepartmentId;
      }
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.applyInfo[key]) {
        this.applyInfo[key].push(fileList);
      } else {
        this.$set(this.applyInfo, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.applyInfo[key].splice(index, 1);
    },
    handleProposerChange(val) {
      this.applyInfo.applicantId = val.id;
      this.applyInfo.proposer = val.userName;
    }
  }
};
</script>

<style lang="scss" scoped>
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
    .file-container {
      max-height: 60px;
      overflow-y: auto;
    }
  }
  .range-radio-group {
    white-space: nowrap;
    &::v-deep {
      .el-checkbox__label {
        padding-left: 4px;
      }
      .el-checkbox {
        margin-right: 8px;
      }
    }
  }
}
.apply-info-form {
  &.mobile-el-form {
    .range-radio-group {
      white-space: normal;
    }
  }
}
</style>
